<?php

class CategoryController extends FrontendController
{
	
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function actionIndex()
	{
		//get product by subcategory
		$product = new Product();
		$criteria = new CDbCriteria();
		$criteria->select = 't.*';
		$criteria->with = 'product';
		$criteria->condition = 't.SubCategoryId="1"';
		$criteria->order = 't.CreateDate DESC';
		$result = $product->findAll($criteria);

		$sub = SubCategory::getAll(1);
		foreach ($sub as $key => $value) {
			//$arr[$key] = count(getProductBySub($value['SubCateId']));
		}
		$this->render('index',array('subcate' => $sub));
	}

	public function countProductBySubSub($id){
		$product = new Product();
		$criteria = new CDbCriteria();
		$criteria->select = 't.*';
		//$criteria->with = 'subcategory';
		//$criteria->join = 'JOIN Photos pt ON pt.ProductId = t.ProductId';
		$criteria->condition = 't.Status="1"';//' and pt.CoverPhoto ="1"';
		$criteria->order = 't.CreateDate DESC';
		$result = $product->findAll($criteria);
	}
	public function actionView($id){
		//get information SIDEBAR
		//get sub
		$subcate = SubCategory::model()->with('category')->findByPk($id);
		//get product
		$product = Product::model()->findAllByAttributes(array('SubCategoryId' => $id));

		$this->render('view',array(
			'product' => $product,
			'sub' => $subcate,
			));
	}
	public function getProductBySub($id){
		$model = new Product();
		$criteria = new CDbCriteria();
		$criteria->select = 't.*';
		$criteria->condition = 't.SubCategoryId="' . $id .'"';
		$criteria->order = 't.CreateDate DESC';
		$result = $model->findAll($criteria);

		return $result;
	}
	public function loadModel($id)
	{
		$model=Category::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	public function searchproduct(){
		// $product = Product::model()->findByAttributes($_POST['id']);
		// if (isset($product)) {
		// 	echo CJSON::encode(1);
		// }
		return CJSON::encode(1);
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='search-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
